from django.db import models
from django.contrib.auth.models import User
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.conf import settings as global_settings


from mercurial import hg, ui
from datetime import datetime, date
import shutil, os
import hgWeb.hg.settings as hg_settings

# Create your models here.

PERMISSIONS = (
    (1,"READ"),
    (2,"READ/WRITE"),
    (3,"OWNER")
)


class RepositoryContext():
    def __init__(self, repo, hash=None) :
#        if hash is None:
#            hash = 'tip'
        repo_path = os.path.join(hg_settings.HG_REPOSITORIES_ROOT,repo.path)
        if hash is None:
            hash = 'tip'
        # get a repo object for the current directory
        
        self.repository = hg.repository(ui.ui(),
                                        repo_path)

        # get a context object for the "rev" revision
        self.ctx = self.repository[hash]
        self.user = self.ctx.user()
        self.description = self.ctx.description()
        self.time= datetime.fromtimestamp(self.ctx.date()[0]).time()
        self.date= date.fromtimestamp(self.ctx.date()[0])
        self.hash = self.ctx #hash
        self.rev = self.ctx.rev()
        self.files_count = len(self.ctx.files())
        self.revision = self.repository[self.rev]
    def __unicode__(self):
        return self.name
    
class Repository(models.Model):
    name = models.SlugField(_("Name"), unique=True)
    description = models.TextField(_('Description'), blank=True,null=True)
    anonymous_access = models.BooleanField(_("Allow Anonymous Viewing"), default=True)
    path = models.CharField(max_length=255)
    members = models.ManyToManyField(User, through='RepositoryUser', verbose_name="list of members")

    
    def __unicode__(self):
        return self.name + ' : ' + self.description
    
    def set_context(self, ctx):
        self.context = ctx
        
    def get_context(self):
        return self.context
    
class RepositoryUser(models.Model):
    repository = models.ForeignKey(Repository)
    user = models.ForeignKey(User)
    permission = models.IntegerField(_('Permission'), choices=PERMISSIONS)

    def __unicode__(self):
        out = u"%s of %s with %s permission" % (self.user,
                self.repository, self.get_permission_display())
        return out
    
class LanguageList(models.Model):
    language = models.CharField(max_length=5, unique=True)
    RepositoriesTitle = models.CharField(max_length=50)
    RepositoryName = models.CharField(max_length=50)
    RepositoryDesc = models.CharField(max_length=50)
    RepositoryAuthor = models.CharField(max_length=50)
    RepositoryTime = models.CharField(max_length=50)
    RepositoryOptions = models.CharField(max_length=50)
    
    def __unicode__(self):
        return self.language
